import time
import requests

from .exceptions import RiskControlError
from .time_utils import getCurTime

def ownRequest(url, method='get', **args):
    # 实现一个请求，如果请求失败，则重试5次
    for i in range(5):
        try:
            if method == 'get':
                response = requests.get(url, **args, verify=False, timeout=2)
            elif method == 'post':
                response = requests.post(url, **args, verify=False, timeout=2)
            else:
                return None
            if "then retry. error code" in response.text:
                print(getCurTime(), "出现风控=>", url, response.json())
            response.encoding = 'utf-8'
            return response
        except Exception as e:
            print(getCurTime(), f"请求失败 {e},重试第{i + 1}次")
            # traceback.print_exc()
            continue
    raise RiskControlError("请求重试多次后，依旧失败")

def process_imgUrl(img_url):
    url = "http://xdrj.lottefuture.com/zxy/V1/Gen2/ed1XF/ModuleController/SearchModule/uploadImg"

    files = [
        ('Img', (f'{int(time.time())}.png', requests.get(img_url).content,
                'image/webp'))
    ]
    res = ownRequest(url, method="post", files=files)
    try:
        return res.json().get("data", None)
    except:
        print(getCurTime(), f"上传图片{img_url}失败,返回的响应=> {res.text if res else None}")
        return None 